package lg.minecraft.plugin.entityclear.task;

import lg.minecraft.plugin.entityclear.template.EntityClearTaskTemplate;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 实体清理任务运行时类
 * 包含任务的运行时状态和执行逻辑
 *
 * @author langle__
 * @version 1.0
 */
public class EntityClearTask {

    @Getter
    private final EntityClearTaskTemplate template;

    @Getter
    @Setter
    private long nextClearTime = 0;

    private Map<Integer, String> messages = Collections.emptyMap();

    public EntityClearTask(@NotNull EntityClearTaskTemplate template) {
        this.template = template;
        this.reset();
    }

    public int clearEntities() {
        int count = 0;
        List<Entity> entities = new ArrayList<>();
        for (World world : Bukkit.getWorlds()) {
            if (!template.testWorld(world)) continue;
            entities.addAll(world.getEntities());
        }
        for (Entity entity : entities) {
            EntityType type = entity.getType();
            if (!template.testEntity(entity) || entity.isDead() || !entity.isValid() || type == EntityType.PLAYER) continue;
            if (template.entityRemover(entity)) count++;
        }
        return count;
    }

    /**
     * 判断是否达到清理时间条件
     *
     * @return 如果当前时间大于等于预定清理时间返回true，否则返回false
     */
    public boolean shouldClear() {
        return System.currentTimeMillis() >= nextClearTime;
    }

    /**
     * 重置清理定时器，设置下一次清理时间
     * 下一次清理时间 = 当前时间 + 间隔时间
     */
    public void reset() {
        this.nextClearTime = System.currentTimeMillis() + template.getClearInterval();
        this.messages = template.getMessages();
    }

    /**
     * 获取距离下次清理的剩余时间（毫秒）
     *
     * @return 剩余时间毫秒数，如果已到清理时间则返回0
     */
    public long getTimeLeft() {
        return nextClearTime - System.currentTimeMillis();
    }

    @Nullable
    public String getMessage(int time, boolean remove) {
        return remove ? messages.remove(time) : messages.get(time);
    }

}
